import 'package:safetymonitor/app/components/device_tree/controller.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/data/entities/home/risk_tree_entity.dart';

///
/// 懒加载子节点：
// 子节点的渲染被推迟到节点展开时，避免了初始时一次性渲染所有的子节点。
// ListView.builder 替换 SingleChildScrollView：
//
// ListView.builder 会根据需要渲染子节点，避免了渲染未显示的节点，减少了性能开销。
// 动画优化：
//
// 将动画持续时间减少为 300ms，提高响应速度。
// 减少不必要的 AnimatedSize 包裹：
//
// 只有在节点展开时才使用 AnimatedSize，减少了不必要的性能开销。
class DeviceTreePage extends StatelessWidget {
  DeviceTreePage({
    required this.selectedEntity,
    required this.onCallBack,
    super.key,
  });

  final RiskTreeEntity selectedEntity;
  final Function(RiskTreeEntity entity) onCallBack;
  final controller = Get.put(DeviceTreeController());

  // 部门数据每一项的显示
  Widget _getTreeView(RiskTreeEntity treeEntity, int level) {
    // final bool isSelected = (treeEntity.id == controller.selectedEntity.id) && treeEntity.nodeType == 4;
    final bool isSelected = treeEntity.id == controller.selectedEntity.id;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          constraints: BoxConstraints(minHeight: 55.w),
          child: Row(
            children: [
              SizedBox(width: 20.w * level),
              treeEntity.children!.isNotEmpty
                  ? GestureDetector(
                      onTap: () {
                        controller.toggleExpand(treeEntity);
                      },
                      child: Icon(
                        treeEntity.isExpand!
                            ? Icons.arrow_drop_down
                            : Icons.arrow_right,
                        size: 18.w,
                      ),
                    )
                  : SizedBox(width: 18.w),
              AppGaps.hGap10,
              Expanded(
                child: Container(
                  padding:
                      EdgeInsets.symmetric(horizontal: 10.w, vertical: 6.w),
                  decoration: BoxDecoration(
                    color: isSelected ? const Color(0xff5C6DFF) : const Color(0xffffffff),
                    borderRadius: BorderRadius.circular(4.w),
                  ),
                  child: Text(
                    treeEntity.nodeName!,
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                      color: isSelected ? const Color(0xffffffff) : const Color(0xff34406D),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ).clickOnce(() {
          controller.clickOnNode(treeEntity);
          onCallBack(treeEntity);
        }),
        if (treeEntity.isExpand!)
          AnimatedSize( //将 AnimatedSize 的使用限制在需要展开/折叠的区域，并避免每个节点都包含该动画效果。
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            child: _buildChildTree(treeEntity, level + 1),
          ),
      ],
    );
  }

  Widget _buildChildTree(RiskTreeEntity treeEntity, int level) {
    if (treeEntity.children == null) return const SizedBox.shrink();

    // 延迟加载子节点
    return Column(
      children: treeEntity.children!.map((item) {
        return _getTreeView(item, level);
      }).toList(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DeviceTreeController>(
      initState: (_) {
        controller.onInitData(selectedEntity);
      },
      init: controller,
      builder: (_) {
        return Expanded(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.w),
            decoration: BoxDecoration(
              color: const Color(0xFFE5E9FF),
              borderRadius: BorderRadius.circular(4.w),
            ),
            child: ListView.builder(//如果树的数据量较大，可以将 SingleChildScrollView 换成 ListView.builder，它可以懒加载和回收滚动区域外的子节点，避免一次性加载整个树结构
             //ListView.builder 的优势是它只渲染当前可见区域的节点，而不是一次性渲染整个列表，这样可以显著提高性能。
              itemCount: controller.treeList.length,
              itemBuilder: (context, index) {
                return _getTreeView(controller.treeList[index], 0);
              },
            ),
          ),
        );
      },
    );
  }
}
